<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="任务状态" name="taskStatus">
              <a-select v-model:value="queryParam.taskStatus" placeholder="请选择任务状态" allow-clear>
                <a-select-option value="未完成">未完成</a-select-option>
                <a-select-option value="已完成">已完成</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
              <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" @expand="handleExpand">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'tasks:tasks:add'"  @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button  type="primary" v-auth="'tasks:tasks:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button  type="primary" v-auth="'tasks:tasks:importExcel'"  preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'tasks:tasks:deleteBatch'">批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
        <!-- 业务呈现按钮 -->
        <a-button type="primary" @click="handleBusinessPresentation" :disabled="selectedRowKeys.length !== 1" preIcon="ant-design:eye-outlined">
          业务呈现
        </a-button>
        <!-- 进入售后按钮 -->
        <a-button type="primary" @click="handleEnterAfterSale" :disabled="selectedRowKeys.length !== 1" preIcon="ant-design:customer-service-outlined" v-auth ="'tasks:tasks:addAfterSale'">
          进入售后
        </a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!-- 展开行 -->
      <template #expandedRowRender="{ record }">
        <TeamMemberTable
          v-if="record.id"
          :taskId="record.id"
          :teamId="record.teamId"
          @refresh-main-table="handleRefreshMainTable"
        />
      </template>


    </BasicTable>
    <!-- 表单区域 -->
    <TasksModal ref="registerModal" @success="handleSuccess"></TasksModal>
    <!-- 业务呈现模态框 -->
    <a-modal
      v-model:open="businessModalVisible"
      title="业务呈现 - 团队成员任务分配"
      width="800px"
      :footer="null"
      @cancel="handleBusinessModalClose"
    >
      <div v-if="businessLoading" style="text-align: center; padding: 50px;">
        <a-spin size="large" />
        <div style="margin-top: 16px;">加载中...</div>
      </div>
      <div v-else-if="businessData.length === 0" style="text-align: center; padding: 50px; color: #999;">
        暂无数据
      </div>
      <div v-else>
        <!-- 优化后的业务呈现展示 -->
        <div class="business-presentation-container">
          <div 
            v-for="(item, index) in businessData" 
            :key="item.id || index"
            class="business-item-wrapper"
          >
            <!-- 任务内容卡片 -->
            <div class="business-item">
              <div class="task-content">
                <div class="task-title">任务内容</div>
                <div class="task-text">{{ item.assignmentContent || '暂无任务内容' }}</div>
              </div>
              <div class="completion-status">
                <div class="status-title">完成程度</div>
                <div class="status-content">
                  <span class="status-text">{{ item.assignmentStatus || '暂无状态' }}</span>
                  <span class="status-icon">
                    <Icon 
                      v-if="isCompleted(item.assignmentStatus)" 
                      icon="ant-design:check-circle-filled" 
                      :style="{ color: '#52c41a', fontSize: '20px' }"
                    />
                    <Icon 
                      v-else 
                      icon="ant-design:close-circle-filled" 
                      :style="{ color: '#ff4d4f', fontSize: '20px' }"
                    />
                  </span>
                </div>
              </div>
            </div>
            
            <!-- 箭头连接线 (除了最后一个项目) -->
            <div v-if="index < businessData.length - 1" class="arrow-connector">
              <Icon 
                icon="ant-design:arrow-down-outlined" 
                :style="{ color: '#1890ff', fontSize: '24px' }"
              />
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" name="tasks-tasks" setup>
  import { ref, reactive, provide } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema, tableProps } from './Tasks.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, addAfterSale } from './Tasks.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import TasksModal from './components/TasksModal.vue'
  import TeamMemberTable from './components/TeamMemberTable.vue'

  import { useUserStore } from '/@/store/modules/user';
  import { defHttp } from '/@/utils/http/axios';
  import { message, Modal } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { h } from 'vue';

  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '任务表',
      api: list,
      columns,
      canResize: false,
      useSearchForm: false,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: async (params) => {
        return Object.assign(params, queryParam);
      },
      ...tableProps, // 添加展开行配置
    },
    exportConfig: {
      name: "任务表",
      url: getExportUrl,
      params: queryParam,
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  // 业务呈现相关
  const businessModalVisible = ref(false);
  const businessLoading = ref(false);
  const businessData = ref([]);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    searchQuery();
  }

  /**
   * 业务呈现事件
   */
  async function handleBusinessPresentation() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请选择一条记录');
      return;
    }

    const selectedRecord = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
    if (!selectedRecord) {
      message.error('未找到选中的记录');
      return;
    }

    if (!selectedRecord.teamId) {
      message.warning('该记录没有关联的团队ID');
      return;
    }

    businessModalVisible.value = true;
    businessLoading.value = true;
    businessData.value = [];

    try {
      console.log('调用业务呈现接口，teamId:', selectedRecord.teamId);
      console.log('选中的记录:', selectedRecord);

      const response = await defHttp.get({
        url: '/teams/teams/queryByTaskId',
        params: { teamId: selectedRecord.teamId }
      });

      console.log('业务呈现接口响应:', response);
      console.log('响应数据类型:', typeof response);
      console.log('响应success:', response?.success);
      console.log('响应result:', response?.result);

      if (true) {
        const data = response || [];
        console.log('原始数据:', data);

        if (Array.isArray(data) && data.length > 0) {
          // 直接使用原始数据，只做必要的字段处理
          businessData.value = data.map((item, index) => {
            console.log(`处理第${index + 1}条数据:`, item);
            return {
              key: item.id || index, // 添加key属性用于表格渲染
              id: item.id,
              name: item.name || '未知成员',
              role: item.role || '未分配',
              productName: item.productName || '暂无产品',
              assignmentContent: item.assignmentContent || item.assignment_content || item.task || '暂无任务内容',
              assignmentStatus: item.assignmentStatus || item.assignment_status || item.completion || '暂无状态',
              // 保留其他原始字段
              teamId: item.teamId,
              teamName: item.teamName,
              createTime: item.createTime,
            };
          });

          console.log('处理后的业务数据:', businessData.value);
        } else {
          console.log('数据为空或格式不正确');
          businessData.value = [];
          message.info('该团队暂无成员数据');
        }
      } else {
        console.error('接口返回失败:', response);
        message.error(response?.message || '获取业务数据失败');
        businessData.value = [];
      }
    } catch (error) {
      console.error('业务呈现接口调用失败:', error);
      console.error('错误详情:', error.message);
      console.error('错误堆栈:', error.stack);
      message.error(`获取业务数据失败: ${error.message || '未知错误'}`);
      businessData.value = [];
    } finally {
      businessLoading.value = false;
    }
  }

  /**
   * 关闭业务呈现模态框
   */
  function handleBusinessModalClose() {
    businessModalVisible.value = false;
    businessData.value = [];
  }

  /**
   * 判断任务是否已完成
   * @param status 完成程度状态
   * @returns boolean
   */
  function isCompleted(status: string): boolean {
    if (!status) return false;
    const completedStatuses = ['已完成', '完成', '100%', '已结束', '结束'];
    return completedStatuses.some(completedStatus => 
      status.includes(completedStatus) || status === completedStatus
    );
  }

  /**
   * 进入售后事件
   */
  async function handleEnterAfterSale() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请选择一条记录');
      return;
    }

    const selectedRecord = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
    if (!selectedRecord) {
      message.error('未找到选中的记录');
      return;
    }

    // 显示确认弹框
    Modal.confirm({
      title: '确认进入售后流程',
      content: h('div', [
        h('div', { style: 'margin-bottom: 16px; font-size: 14px; color: #666;' }, '您即将进入售后流程，请确认操作'),
        h('div', { style: 'background: #f5f5f5; padding: 12px; border-radius: 6px; border-left: 4px solid #1890ff;' }, [
          h('div', { style: 'font-weight: 500; margin-bottom: 8px; color: #333;' }, '选中任务信息：'),
          h('div', { style: 'color: #666; line-height: 1.6;' }, [
            h('div', `任务名称：${selectedRecord.taskName || '暂无'}`),
            h('div', `任务状态：${selectedRecord.taskStatus || '暂无'}`),
            h('div', `任务描述：${selectedRecord.taskDescription || '暂无'}`),
          ])
        ])
      ]),
      okText: '确认进入',
      cancelText: '取消',
      okType: 'primary',
      width: 480,
      centered: true,
      onOk: async () => {
        try {
          console.log('调用进入售后接口，数据：', selectedRecord);
          const response = await addAfterSale(selectedRecord);
          
          if (response.success) {
            message.success('成功进入售后流程');
            // 可以在这里添加跳转到售后页面的逻辑
            // 或者刷新表格数据
            reload();
          } else {
            message.error(response.message || '进入售后失败');
          }
        } catch (error) {
          console.error('进入售后接口调用失败:', error);
          message.error(`进入售后失败: ${error.message || '未知错误'}`);
        }
      }
    });
  }

  /**
   * 处理展开行事件
   */
  function handleExpand(expanded, record) {
    console.log('展开行:', expanded, '记录ID:', record.id, '团队ID:', record.teamId);
    // 展开行的处理逻辑由子组件自动处理
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }
  
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
   
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }
   
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
   
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
   
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
   
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'tasks:tasks:edit'
      },
    ];
  }
   
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      }, {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        auth: 'tasks:tasks:delete'
      }
    ]
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  // 处理刷新主表数据的事件
  function handleRefreshMainTable() {
    console.log('接收到刷新主表数据的事件，开始重新加载任务表...');

    // 重新加载表格数据
    reload();

    console.log('任务表数据重新加载完成');
  }

  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }
  


</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
    .ant-form-item:not(.ant-form-item-with-help){
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),:deep(.ant-input-number){
      width: 100%;
    }
  }

  // 业务呈现样式
  .business-presentation-container {
    padding: 16px;
    max-height: 500px;
    overflow-y: auto;
    
    .business-item-wrapper {
      margin-bottom: 0;
      
      .business-item {
        background: #fafafa;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        padding: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.3s ease;
        
        &:hover {
          background: #f0f9ff;
          border-color: #1890ff;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
        }
        
        .task-content {
          flex: 1;
          margin-right: 20px;
          
          .task-title {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
            font-weight: 500;
          }
          
          .task-text {
            font-size: 16px;
            color: #333;
            line-height: 1.5;
            word-break: break-word;
          }
        }
        
        .completion-status {
          min-width: 120px;
          text-align: center;
          
          .status-title {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
            font-weight: 500;
          }
          
          .status-content {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            
            .status-text {
              font-size: 16px;
              color: #333;
              font-weight: 500;
            }
            
            .status-icon {
              display: flex;
              align-items: center;
            }
          }
        }
      }
      
      .arrow-connector {
        text-align: center;
        padding: 15px 0;
        
        :deep(.anticon) {
          animation: bounce 1.5s infinite;
        }
      }
    }
  }

  @keyframes bounce {
    0%, 20%, 50%, 80%, 100% {
      transform: translateY(0);
    }
    40% {
      transform: translateY(-3px);
    }
    60% {
      transform: translateY(-2px);
    }
  }
</style>
